package net.jirox.staticengine;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.jirox.staticengine.exceptions.AuthenticationRequiredException;
import net.jirox.staticengine.persistent.User;

import org.apache.commons.codec.binary.Base64;

public class BasicAuth {
	Map<String, String> userMap = new HashMap<String, String>();

	private static final Logger log = Logger.getLogger(BasicAuth.class.getName());

	private boolean tryAuth(String authHeader, PersistenceManager pm) {
		if (authHeader == null) return false;
		String[] pair = authHeader.split(" ");
		if (pair.length != 2) {
			log.severe("failed to parse authHeader: " + authHeader);
			return false;
		}
		if (!pair[0].equals("Basic")) { // schema
			log.severe("unsupported login scheme: " + pair[0]);
			return false;
		}
		String decoded = new String(Base64.decodeBase64(pair[1].getBytes()));
		String[] userPass = decoded.split(":");
		if (userPass.length != 2 || !User.isExists(userPass[0], userPass[1], pm)) {
			log.severe("AuthFailure: " + decoded);
			return false;
		}
		return true;
	}

	public void send401(ServletResponse response, String realm, String message) throws IOException {
		HttpServletResponse res = (HttpServletResponse) response;
		res.setStatus(401);
		res.setHeader("WWW-Authenticate", "Basic realm=" + realm);
		res.getWriter().println("<body><h1>" + message + "</h1></body>\n");
		return;
	}

	String REALM = "Basic"; // default

	public void auth(ServletRequest request, ServletResponse response, PersistenceManager pm)
			throws AuthenticationRequiredException {
		HttpServletRequest req = (HttpServletRequest) request;
		String authHeader = req.getHeader("Authorization");
		if (!tryAuth(authHeader, pm)) throw new AuthenticationRequiredException();// send401(response, REALM, "realm");
	}
}
